$(function(){
    getDataList();
    getMyCouponList();
});
var volist = []
//隐藏注册页面
$(".close").on("click",function(){
    $(".modal_box,#zz").hide();
    $('.r_username').val('');
    $('.r_password').val('');
    $('.r_name').val('');
    $('.r_sex').val('');
    $('.r_telephone').val('');
    $('.r_email').val('');
});
//获取数据
function getDataList () {
    $.ajax({
        type:"get",
        url: upUrl + "/cart/front/cartList",
        dataType: "json",
        data: {
            pageNum: 1,
            pageSize: 100000,
        },
        success:function(data){
            volist = data.result.records;
            var orderBody = '';
            var sum = 0;
            var number = 0;
            $.each(data.result.records, function (index, val) {
                sum += Number(val.price) * Number(val.number)
                number += Number(val.number)
                orderBody += '<div class="order_list">\
                    <div class="order_img">\
                        <img src="' + val.rimage + '" alt="">\
                    </div>\
                    <div class="caiName">' + val.dishName + '</div>\
                    <div class="o_price1">' + val.price + '</div>\
                    <div class="o_price">\
                        <span class="less">-</span>\
                        <div class="num">' + val.number + '</div>\
                        <span class="puls">+</span>\
                    </div>\
                    <div class="caiName"><span onclick="deleteOrder(' + val.id + ')" class="btn-valid">删除</span></div>\
                </div>'
            })
            $('.list_box').html(orderBody);
            $('.totalMoney').html(sum)
            $('.subtotalMoney').html(sum)
            $('.preferentialMoney').html(0);
            $('.totalNumber').html(number)
            // 加号事件
            var i_btn = document.getElementsByClassName("puls");
            for (var k = 0; k < i_btn.length; k++) {
                i_btn[k].onclick = function() {
                    bt = this;
                    node = bt.parentNode.childNodes[3];
                    num = node.innerText;
                    num = parseInt(num);
                    num++;
                    node.innerText = num;
                    var sum = 0;
                    var number = 0;
                    $(".order_list").each(function(i){
                        number += Number($(this).children("div .o_price").children("div .num").html())
                        sum +=Number($(this).children("div .o_price1").html()) * Number($(this).children("div .o_price").children("div .num").html())
                        // console.log(Number($(this).children("div .o_price1").html()))
                        // console.log($(this).children("div .o_price").children("div .num").html())
                    });
                    console.log(sum)
                    $('.totalMoney').html(sum)
                    $('.subtotalMoney').html(sum)
                    $('.preferentialMoney').html(0);
                    $('.totalNumber').html(number)
                    $('#selectCoupon').val([0]);
                }
            }
            // 减号事件
            var d_btn  = document.getElementsByClassName("less");
            for (var k = 0; k < i_btn.length; k++) {
                d_btn[k].onclick = function() {
                    bt = this;
                    node = bt.parentNode.childNodes[3];
                    num = node.innerText;
                    num = parseInt(num);
                    if (num > 0) {
                        num--;
                    }
                    node.innerText = num;
                    var sum = 0;
                    var number = 0;
                    $(".order_list").each(function(i){
                        number += Number($(this).children("div .o_price").children("div .num").html())
                        sum +=Number($(this).children("div .o_price1").html()) * Number($(this).children("div .o_price").children("div .num").html())
                        // console.log(Number($(this).children("div .o_price1").html()))
                        // console.log($(this).children("div .o_price").children("div .num").html())
                    });
                    console.log(sum)
                    $('.totalMoney').html(sum)
                    $('.subtotalMoney').html(sum)
                    $('.preferentialMoney').html(0);
                    $('.totalNumber').html(number)
                    $('#selectCoupon').val([0]);
                }
            }
        }
    })
}

function getMyCouponList(){
    $.ajax({
        type:"get",
        url: upUrl + "/coupon/front/myCouponList",
        dataType: "json",
        data: {
            pageNum: 1,
            pageSize: 10000,
        },
        success:function(data){
            var testList = data.result.records;
            total = data.result.total;
            $('#selectCoupon').html("");
            var orderBody = '<option value=\"0\">请选择</option>';
            $.each(testList, function (index, val) {
                orderBody += '<option value='+val.amount+'>'+val.name+'['+val.introduction+']'+'价值'+val.amount+'元'+'</>'
            })
            console.log("拼接：",orderBody)
            $('#selectCoupon').html(orderBody);
        }
    })
}

function chooseCoupon(){
    var val = $('#selectCoupon').val();
    console.log("选择优惠卷金额：",val)
    $('.preferentialMoney').html(val);
    var totalMoney = $(".totalMoney").text();
    // var totalMoney = $('.totalMoney').val();
    console.log("总金额：",totalMoney)
    var che = Number(totalMoney)-Number(val);
    console.log("差额 ：",che)
    if(Number(val)<Number(totalMoney)){
        var number = totalMoney-val;
        $('.subtotalMoney').html(number);
    }else {
        $('.subtotalMoney').html(0);
    }
}

// 全选或取消全选
//页面加载的时候,所有的复选框都是未选中的状态
function checkOrCancelAll(){
    //1.获取checkbo的元素对象
    var chElt=document.getElementById("chElt");
    //2.获取选中状态
    var checkedElt=chElt.checked;
    console.log(checkedElt)
    //3.若checked=true,将所有的复选框选中,checked=false,将所有的复选框取消
    var allCheck=document.getElementsByName("interest");
    //4.循环遍历取出每一个复选框中的元素
    //var mySpan=document.getElementById("mySpan");
    if(checkedElt){
        //全选
        for(var i=0;i<allCheck.length;i++){
            //设置复选框的选中状态
            allCheck[i].checked=true;
        }
        //mySpan.innerHTML="取消全选";
    }else{
        //取消全选
        for(var i=0;i<allCheck.length;i++){
            allCheck[i].checked=false;
        }
        //mySpan.innerHTML="全选";
    }
}
// 获取选中的数据
$("#select_button").on('click',function(){
    var checkids = [];
    var data = [];
    $("input[name='interest']:checked").each(function(i){
        console.log($(this).val());
        checkids[i] = $(this).val();
    });
    if(checkids.length<=0){
        $.notify('请选择单',{status: "danger"});
    }else{
        console.log(checkids);
        // $("#dgFlowList").find(":checkbox:checked").each(function(){
        // var val = $(this).parents("tr").text();
        // data.push(val);
    // });
        console.log(data);
    }
});
var checkids = [];
$("#xiadan").on("click",function(){
    // $("input[name='interest']:checked").each(function(i){
    //     checkids[i] = $(this).val();
    // });
    volist.map((item)=>{
        checkids.push(item.dishId);
    })
    getAddressList();
    // if(checkids.length<=0){
    //     toastr.warning("请选择订单列表!");
    // }else{
    //
    // }
})
// 单个check事件
function checkClick () {
    var chElt=document.getElementById("chElt");
    var checkedElt=chElt.checked;
    var allCheck=document.getElementsByName("interest");
    var arr = []; 
    for(var key in allCheck){
        if(!allCheck.hasOwnProperty(key)){
            continue;
        }
        var item = {};
        item[key] = allCheck[key];
        arr.push(item);
    }
    var flag = arr.some((item)=>{return item.checked == false})
}
function getAddressList () {
    $.ajax({
        type:"get",
        url: upUrl + "/diningTable/front/getUnUseTableList",
        dataType: "json",
        data: {},
        success:function(data){
            var testList = data.result;
            if (testList.length == 0) {
                toastr.error('暂无可使用餐台，请联系工作人员处理！');
            } else {
                total = data.result.total;
                var orderBody = '';
                $.each(testList, function (index, val) {
                    orderBody += '<div class="order_list1">\
                            <div><input type="radio" name="radioName" class="checkout"; value="' + val.id + '" /></div>\
                            <div class="receiver">' + val.name + '</div>\
                            <div>' + val.tableTypeStr + '</div>\
                        </div>'
                })
                $('.item_box').html(orderBody);
                $(".modal_box,#zz").show();
            }
        }
    })
}
var tableName = '';
// 获取餐台单选的数据
$("#addressConfim").on('click',function(){
    var radioids = [];
    $("input[name='radioName']:checked").each(function(i){
        //获取选中的餐台名称
        tableName = $(this).parent().siblings('.receiver').html();
        console.log("209+++++++++"+tableName);
        //获取选中的餐台
        radioids[i] = $(this).val();
    });
    if(radioids.length<=0){
        toastr.warning("请选择餐台!");
    }else{
       // 下单接口
        $.ajax({
            type:"post",
            url: upUrl + "/orderInfo/addOrderInfo",
            data: {
                dishList: checkids.toLocaleString(),
                diningTable: tableName,
                diningTableId: radioids[0],
                price: $('.subtotalMoney').html(),
                preferentialPrice: $('.preferentialMoney').html(),
                totalPrice: $('.totalMoney').html(),
            },
            success:function(data){
                if (data.code == 200) {
                    toastr.success("下单成功!");
                    $(".modal_box,#zz").hide();
                    getDataList();
                } else {
                    toastr.error(data.message);
                }
            }
        })
    }
});
// 地址弹窗取消事件
function addressCancel () {
    var allCheck=document.getElementsByName("radioName");
    console.log(allCheck)
    for(var i=0;i<allCheck.length;i++){
        allCheck[i].checked=false;
    }
    $(".modal_box,#zz").hide();
}
// 删除事件
function deleteOrder (val) {
    $.ajax({
        type:"post",
        url: upUrl + "/cart/deleteCart",
        data: {
            id: val,
        },
        success:function(data){
            if (data.code == 200) {
                toastr.success("删除成功!");
                getDataList();
            } else {
                toastr.error(data.message);
            }
        }
    })
}